package com.guigui.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigui.common.constant.ProductConstant;
import com.guigui.common.utils.PageUtils;
import com.guigui.common.utils.Query;
import com.guigui.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.guigui.gulimall.product.dao.AttrDao;
import com.guigui.gulimall.product.dao.AttrGroupDao;
import com.guigui.gulimall.product.dao.CategoryDao;
import com.guigui.gulimall.product.entity.*;
import com.guigui.gulimall.product.service.AttrService;
import com.guigui.gulimall.product.service.ProductAttrValueService;
import com.guigui.gulimall.product.vo.AttrResponseVo;
import com.guigui.gulimall.product.vo.AttrVo;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrService attrService;

    @Autowired
    private AttrGroupServiceImpl attrGroupService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryAttrBasePage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        // 分类id不为0，查询全部
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }

        // 检索关键字不为空，加上检索条件
        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)) {
            queryWrapper.and((wrapper -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            }));
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        // 增加分类名、组名属性
        List<AttrEntity> attrEntityList = page.getRecords();

        List<AttrResponseVo> responseVos = attrEntityList.stream().map((attrEntity) -> {
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            BeanUtils.copyProperties(attrEntity, attrResponseVo);

            if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
                // 查出并设置组名
                if (attrEntity.getAttrId() != null) {
                    AttrAttrgroupRelationEntity attrgroupRelation = attrAttrgroupRelationDao.selectOne(
                            new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId())
                    );
                    if (attrgroupRelation != null && attrgroupRelation.getAttrGroupId() != null) {
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelation.getAttrGroupId());
                        attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }

            // 查出并设置分类名
            if (attrEntity.getCatelogId() != null) {
                CategoryEntity categoryEntity = categoryDao.selectOne(
                        new QueryWrapper<CategoryEntity>().eq("cat_id", attrEntity.getCatelogId())
                );
                attrResponseVo.setCatelogName(categoryEntity.getName());
            }
            return attrResponseVo;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(responseVos);
        return pageUtils;
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);

        this.save(attrEntity);

        // 级联更新到关联表,只有类型为1时才需要更行关联关系
        if (attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public AttrResponseVo getAttrRespVo(Long attrId) {
        AttrResponseVo attrResponseVo = new AttrResponseVo();

        AttrEntity attrEntity = attrService.getOne(
                new QueryWrapper<AttrEntity>().eq("attr_id", attrId)
        );

        if (attrEntity != null) {
            BeanUtils.copyProperties(attrEntity, attrResponseVo);

            // 设置路径
            attrResponseVo.setCatelogPath(new ArrayList<>(3));
            attrGroupService.findCategories(attrEntity.getCatelogId(), attrResponseVo.getCatelogPath());

        }

        return attrResponseVo;
    }

    @Override
    public void updateAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);

        this.saveOrUpdate(attrEntity);
        Long attrId = attrVo.getAttrId();
        Long attrGroupId = attrVo.getAttrGroupId();
        if (attrGroupId != null) {
            attrAttrgroupRelationDao.update(null, new UpdateWrapper<AttrAttrgroupRelationEntity>().set("attr_group_id", attrGroupId).eq("attr_id", attrId));
        }

    }

    @Override
    public List<AttrEntity> getAttrRelation(Long attrgroupId) {
        List<AttrEntity> attrEntityList = null;

        // relation表中关联的attr_id
        List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId)
        );

        // 通过attr_id查询出对应记录
        if (relationEntityList != null && relationEntityList.size() > 0) {
            List<Long> attrIdList = relationEntityList.stream()
                    .map(AttrAttrgroupRelationEntity::getAttrId)
                    .collect(Collectors.toList());

            attrEntityList = this.listByIds(attrIdList);
        }

        return attrEntityList;
    }

    @Override
    public PageUtils getAttrNoRelation(Map<String, Object> params, Long attrgroupId) {

        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        // 查询出所有当前组id的基本属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId);
        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)) {
            queryWrapper.and(w -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        List<AttrEntity> attrEntityListList = page.getRecords();

        // 当前组已经在使用的基本属性
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntityList = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId)
        );

        List<Long> collect = attrgroupRelationEntityList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        if (collect.size() > 0) {
            List<AttrEntity> attrEntityList = this.listByIds(collect);
            // 过滤掉当前请求attrgroupId的分类
            attrEntityListList.removeAll(attrEntityList);
        }

        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        return this.baseMapper.selectSearchAttrIds(attrIds);
    }
}